package com.googlecode.umlsynch.rpc.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class TConfigReader {
	private ArrayList configs = new ArrayList();
	private TDebug debug;
	public TConfigReader(String filename, IDebug dbg) {
		debug = new TDebug(dbg);
		try {
			File f = new File(filename);
			BufferedReader input =  new BufferedReader(new FileReader(f));
			String line = null;
			TConfig cfg = null;
			while ((line = input.readLine()) != null) {
				String[] options = line.split(":");
				if (options.length == 2) {
					if (options[0].equals("Service")) {
						if (cfg != null) {
							configs.add(cfg);
						}
						cfg = new TConfig();
						cfg.service = options[1];
					}
					if (cfg != null) {
						if (options[0].equals("Host")) {
							cfg.hostname = options[1]; 
						}
						if (options[0].equals("Port")) {
							cfg.port = Integer.parseInt(options[1]);
						}
						if (options[0].equals("Protocol")) {
							if (options[1] == "SIMPLE_SERIALIZABLE") {
								cfg.protocol = "SimpleRMI";
							} else {
								debug.Warning("Support \"SIMPLE_SERIALIZABLE\" only");
							}
						}						
					} else {
						debug.Error("\"Service\" should be declared");
					}
				} else {
					debug.Error("Number of options should be two");
				}
			}

			
		} catch (FileNotFoundException e) {
			debug.Error(e.getLocalizedMessage() + " filename: " + filename);
		} catch (IOException e) {
			debug.Error(e.getLocalizedMessage() + " filename: " + filename);
		}
		
	}
	
	public TConfig getConfig(String config) {
		Iterator iter = configs.iterator();
		while (iter.hasNext()) {
			TConfig cfg  = (TConfig) iter.next();
			if (cfg.service.equals(config)) {
				return cfg;
			}
		}
		return null;		
	}
	
	public int getReadedCount() {
		return configs.size();
	}
}
